package com.around.test.m3u8;

import cn.hutool.core.io.IoUtil;
import com.around.test.m3u8.util.AesUtils;
import com.around.test.m3u8.util.M3U8Util;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

public class M3U8Dec {
   private static String output="D:\\test\\";
    public static void main(String[] args) throws IOException {
        String keyUrl="https://gzgd.operadeer.com/sec";
        String folder="D:\\test\\tp";

        InputStream inputStream = M3U8Util.getInputStream(keyUrl, 3);
        byte[] keys= IOUtils.toByteArray(inputStream);
        System.out.println(keys);
        File f =new File(folder);
        handlerFile(f, keys);

    }

    private static void handlerFile(File f, byte[] keys) throws IOException {

        File[] files = f.listFiles();
        List<File> fileList = Arrays.asList(files);
        Collections.sort(fileList, (o1, o2) -> {
            if (o1.isDirectory() && o2.isFile())
                return -1;
            if (o1.isFile() && o2.isDirectory())
                return 1;
            if(o1.getName().length()!=o2.getName().length()){
                return o1.getName().length()-o2.getName().length();
            }
            return o1.getName().compareTo(o2.getName());
        });
        String fileName =fileList.get(0).getName();
        FileOutputStream fos = new FileOutputStream(output+fileName);
        for (int i = 0; i < fileList.size(); i++) {
            File file = fileList.get(i);
            if(file.isDirectory()){
                if(file.listFiles()!=null&&file.listFiles().length>0){
                    handlerFile(file,keys);
                }
                continue;
            }
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream in= AesUtils.decryptCBC(fileInputStream, keys,null);
            if( in!=null){
                IOUtils.copyLarge(in, fos);
                in.close();
            }


            fileInputStream.close();
        }
    }
}
